package com.hig.utils;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeNode {
    private Long id; // 节点ID
    private Long parentId; // 父节点ID
    private String name; // 节点名称
    private List<TreeNode> children = new ArrayList<>(); // 子节点列表

    public TreeNode() {}

    public TreeNode(Long id, Long parentId, String name) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
    }

    // Getter 和 Setter
    public Long getId() {
        return id;
    }

    public TreeNode setId(Long id) {
        this.id = id;
        return this;
    }

    public Long getParentId() {
        return parentId;
    }

    public TreeNode setParentId(Long parentId) {
        this.parentId = parentId;
        return this;
    }

    public String getName() {
        return name;
    }

    public TreeNode setName(String name) {
        this.name = name;
        return this;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public TreeNode setChildren(List<TreeNode> children) {
        this.children = children;
        return this;
    }

    /**
     * 构建树形结构
     *
     * @param nodes 节点列表
     * @param rootParentId 根父ID
     * @return 树形结构的根节点列表
     */
    public static List<TreeNode> buildTree(List<TreeNode> nodes, Long rootParentId) {
        // 以 ID 为键，节点为值的 Map
        Map<Long, TreeNode> nodeMap = new HashMap<>();
        for (TreeNode node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        // 构建树
        List<TreeNode> roots = new ArrayList<>();
        for (TreeNode node : nodes) {
            if (node.getParentId().equals(rootParentId)) {
                roots.add(node); // 找到根节点
            } else {
                // 将子节点添加到其父节点的 children 中
                TreeNode parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        return roots;
    }
}
